#!/usr/bin/lua

local juci = require("juci.core");
local json = require("juci.json");

local function dir_tree(src, obj)
	local list = juci.shell("find %s -type d | sort 2>/dev/null", src);
	if(list == "") then return nil; end
	local root = { }; 
	for line in list:gmatch("[^\n\r]+") do
		local parent = root; 
		local path = "/";
		for node in line:gmatch("[^/]+") do
			path = path .. node .. "/"; 
			if not parent[node] then 
				parent[node] = { path = path, children = {} }; 
			end
			parent = parent[node].children; 
		end
	end
	return root; 
end

local function folder_tree()
	local tree = dir_tree("/mnt/");
	print(json.encode(tree)); 
end
	
local function autocomplete(opts) 
	if(type(opts.path) ~= "string")
	then
		return 1;
	end
	opts.path = "/mnt/"..opts.path.."*"; 
	local stdout = juci.shell("find \"$(dirname %s)\" -name \"$(basename %s)\" -maxdepth 1 -type d | sed 's/^\\/mnt//g' 2>/dev/null | sed 's|$|/|g'", opts.path, opts.path);
	local result = { folders = {} }
	for line in stdout:gmatch("[^\r\n]+") do 
		table.insert(result.folders, line); 
	end 
	print(json.encode(result));
end

local function get_status(opts)
	local info = juci.shell("wget -q -O - http://127.0.0.1:8200 | sed 's/<tr[^>]*>/\\n/g' | sed 's/<[^>]*>/\\t/g'"); 
	local result = { count = {} }; 
	for line in info:gmatch("[^\r\n]+") do 
		local field,value = line:match("%s+([^\t]+)%s+(%S+)%s+");  
		if(field == "Audio files") then result.count.audio = tonumber(value); end 
		if(field == "Video files") then result.count.video = tonumber(value); end 
		if(field == "Image files") then result.count.image = tonumber(value); end 
	end
	print(json.encode(result)); 
end

juci.ubus({
	["folder_tree"] = folder_tree,
	["autocomplete"] = autocomplete,
	["status"] = get_status
}, arg);
